package com.wuzhun.wxmp.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wuzhun.wxmp.common.ResultCode;
import com.wuzhun.wxmp.common.ServiceException;
import com.wuzhun.wxmp.model.entity.Setting;
import com.wuzhun.wxmp.service.ISettingService;
import com.wuzhun.wxmp.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 访问限制
 *
 * @author Paulin
 * @date 2023/7/24 15:43
 */
@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccessLimitInterceptor.class);
    @Resource
    private ISettingService settingService;
    public static final String WECHAT_API_PRE = "/wechat/";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        // 微信接口不受限制
        if (requestURI.startsWith(WECHAT_API_PRE)) {
            return true;
        }
        Setting setting = settingService.getOne(new QueryWrapper<Setting>().eq("name", "ipWhiteList"));
        String ip = IpUtil.getIpAddress(request);
        // 未设置白名单禁止访问
        if (setting == null || StringUtils.isEmpty(setting.getValue())) {
            LOGGER.error("access denied url:{}, ip:{}", request.getRequestURI(), ip);
            throw new ServiceException(ResultCode.ACCESS_DENIED);
        }
        List<String> ipWhiteList = JSONObject.parseArray(setting.getValue(), String.class);
        // 禁止白名单以外的ip访问
        if (CollectionUtils.isEmpty(ipWhiteList) || !ipWhiteList.contains(ip)) {
            LOGGER.error("access denied url:{}, ip:{}", request.getRequestURI(), ip);
            throw new ServiceException(ResultCode.ACCESS_DENIED);
        }
        return true;
    }
}
